package com.miao.teacher.widget;

import java.util.ArrayList;
import java.util.List;

import com.miao.teacher.ui.R;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class ExamplePlayer {
	public String[] Arrs;

	public List<AudiosDes> mAudiosList = new ArrayList<AudiosDes>();

	private Context context;

	public int totalTime = 0;

	public int lineLong = 0;

	public int currentIndex = 0;

	public int currentLong = 0;

	public Bitmap mBitmap;

	public Paint paint;

	public AudiosDes curAudios = null;

	public int lineHeight = 6;

	public Canvas canvasTemp;

	public Runnable runnable = null;

	private Handler handler;

	private int currTotalTime = 0;

	public View view;

	public ImageView cImg;

	public ImageView rImg;

	private boolean isStart = false;

	public ExamplePlayer(Context c, Handler h, String[] a, int l, View v,
			ImageView cI, ImageView rI) {
		Arrs = a;
		context = c;
		lineLong = l;
		handler = h;
		view = v;
		cImg = cI;
		rImg = rI;
		cImg.setVisibility(View.INVISIBLE);
		rImg.setVisibility(View.INVISIBLE);
		setImage();
		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				getTotalTime();
			}
		}.start();
	}

	public void playVoice() {
		try{
		isStart = true;
		if (currentIndex < mAudiosList.size()) {
			curAudios = mAudiosList.get(currentIndex);
			curAudios.mediaPlayer
					.setOnCompletionListener(new OnCompletionListener() {
						@Override
						public void onCompletion(MediaPlayer mp) {
							// TODO Auto-generated method stub
							currTotalTime += mp.getDuration();
							currentIndex++;
							playVoice();
						}
					});
			curAudios.mediaPlayer.start();
			if (runnable == null) {
				runnable = new Runnable() {
					@Override
					public void run() {
						try{
						handler.postDelayed(runnable, 100);
						int c = currTotalTime
								+ curAudios.mediaPlayer.getCurrentPosition();
						int x = (int) ((c * 1.0 / totalTime) * lineLong);
						drawLine(currentLong, x);
						currentLong = x;
						}catch(Exception er)
						{}
					}
				};
				handler.postDelayed(runnable, 100);
			}
		} else {
			currentIndex = 0;
		}
		}catch(Exception er)
		{}
	}

	public void doPause() {
		if (curAudios != null) {
			curAudios.mediaPlayer.pause();
		}
	}

	public void doStop() {
		try {
			curAudios.mediaPlayer.pause();
			for(int i=0;i<mAudiosList.size();i++)
			{
				AudiosDes audios=mAudiosList.get(i);
				audios.mediaPlayer.stop();
				audios.mediaPlayer.release();
				runnable=null;
			}
		} catch (Exception er) {

		}
	}

	public void doRestart() {
		if (isStart && curAudios != null) {
			curAudios.mediaPlayer.start();
		} else if (!isStart) {
			playVoice();
		}
	}

	public boolean isPlaying() {
		if (curAudios == null) {
			return false;
		} else {
			if (curAudios.mediaPlayer.isPlaying()) {
				return true;
			} else {
				return false;
			}
		}
	}

	/*
	 * 设置图片
	 */
	private void setImage() {
		Bitmap bmp = ((BitmapDrawable) context.getResources().getDrawable(
				R.drawable.img_empty)).getBitmap();
		mBitmap = Bitmap.createScaledBitmap(bmp, lineLong, dip2px(lineHeight),
				true);
		this.paint = new Paint();
		this.paint.setAntiAlias(true); // 消除锯齿
		this.paint.setStyle(Paint.Style.STROKE); // 绘制空心圆
		setPaintGray();
		canvasTemp = new Canvas(mBitmap);
		canvasTemp.drawLine(0, 0, lineLong, 0, paint);
		view.setBackgroundDrawable(new BitmapDrawable(mBitmap));
	}

	/*
	 * 画线
	 */
	private void drawLine(int startX, int endX) {
		if (curAudios != null) {
			if (curAudios.isRevise == 0) {
				cImg.setVisibility(View.VISIBLE);
				rImg.setVisibility(View.INVISIBLE);
				int w = cImg.getWidth();
				LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
						LinearLayout.LayoutParams.WRAP_CONTENT,
						LinearLayout.LayoutParams.WRAP_CONTENT);
				param.setMargins(endX + 5, 0, 0, 0);
				cImg.setLayoutParams(param);
				setPaintGreen();
			} else {
				cImg.setVisibility(View.INVISIBLE);
				rImg.setVisibility(View.VISIBLE);
				int w = rImg.getWidth();
				LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
						LinearLayout.LayoutParams.WRAP_CONTENT,
						LinearLayout.LayoutParams.WRAP_CONTENT);
				param.setMargins(endX + 5, 0, 0, 0);
				rImg.setLayoutParams(param);
				setPaintRed();
			}
			canvasTemp.drawLine(startX, 0, endX, 0, paint);
			view.setBackgroundDrawable(new BitmapDrawable(mBitmap));
		}
	}

	/*
	 * 获取所有语音长度
	 */
	private void getTotalTime() {
		if (Arrs != null) {
			mAudiosList.clear();
			for (int i = 0; i < Arrs.length; i++) {
				try {
					AssetManager assetManager = context.getAssets();
					AssetFileDescriptor afd = assetManager.openFd("r/"
							+ Arrs[i]);
					MediaPlayer mediaPlayer = new MediaPlayer();
					mediaPlayer.setDataSource(afd.getFileDescriptor(), afd
							.getStartOffset(), afd.getLength());
					mediaPlayer.prepare();
					totalTime += mediaPlayer.getDuration();
					AudiosDes audios = new AudiosDes();
					audios.length = mediaPlayer.getDuration();
					audios.mediaPlayer = mediaPlayer;
					audios.url = Arrs[i];
					if (Arrs[i].startsWith("c")) {
						audios.isRevise = 0;
					} else {
						audios.isRevise = 1;
					}
					mAudiosList.add(audios);
				} catch (Exception er) {
				}
			}
		}
	}

	private void setPaintGreen() {
		this.paint.setARGB(255, 106, 180, 159);
		this.paint.setStrokeWidth(dip2px(lineHeight));
	}

	private void setPaintRed() {
		this.paint.setARGB(255, 223, 96, 91);
		this.paint.setStrokeWidth(dip2px(lineHeight));
	}

	private void setPaintGray() {
		this.paint.setARGB(255, 190, 190, 190);
		this.paint.setStrokeWidth(dip2px(lineHeight));
	}

	static class AudiosDes {
		public int length;
		public int isRevise;
		public String url;
		public MediaPlayer mediaPlayer;
	}

	public int dip2px(float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}
}
